package cn.com.ghy.android.widget;

import java.io.Serializable;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import cn.com.ghy.android.bean.LoginInfoBean;
import cn.com.ghy.android.bean.UnitInfoBean;
import cn.com.ghy.android.exception.DisposeException;
import cn.com.ghy.android.service.AutoUpdateService;
import cn.com.ghy.android.service.LoginOpeService;
import cn.com.ghy.android.service.NoteOpeService;
import cn.com.ghy.android.service.OrderOpeService;
import cn.com.ghy.android.util.CommonStatic;
import cn.com.ghy.android.util.CommonUtil;

/**
 * @软件著作权:金红叶纸业集团有限公司
 * @系统名称:SFA系统
 * @Description:用户登录activity
 * @author wuz  @date 2011-5-3 09:21:16
 * @版本历史:v1.0
 * @Copyright:Copyright (c) 2011-2012 
 */

public class Login extends Activity {

	private EditText txtUserid = null;
	private EditText txtUserpwd = null;
	private CheckBox chkUserid = null;
	private CheckBox chkUserpwd = null;
	private Button btnLogin = null;
	private Button btnCancel = null;
	private TextView labTxtVersion = null;

	private Bundle bundle = null;
	private SharedPreferences sp = null;

	private Boolean isLoading = false;
	private ProgressDialog progressDialog = null;
	private AutoUpdateService autoUpdateService = null;

	private HttpThread thread = null;
	boolean flag = false;

	private String userid = null;
	private String userpwd = null;

	private DisposeException disposeException = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_system);
		getSession();
		findViews();
		checkIfRemember();
		addListeners();
	}

	private void findViews() {
		txtUserid = (EditText) this.findViewById(R.id.txtUserid);
		txtUserid.setFilters(CommonUtil.inputFilter);
		txtUserpwd = (EditText) this.findViewById(R.id.txtUserpwd);
		txtUserpwd.setFilters(CommonUtil.inputFilter);
		txtUserpwd.setKeyListener(CommonUtil.passwdListener);
		btnLogin = (Button) this.findViewById(R.id.btnLogin);
		btnCancel = (Button) this.findViewById(R.id.btnCancel);
		chkUserid = (CheckBox) this.findViewById(R.id.chkUserid);
		chkUserpwd = (CheckBox) this.findViewById(R.id.chkUserpwd);
		labTxtVersion = (TextView) findViewById(R.id.labTxtVersion);
		try {
			labTxtVersion.setText("版本:"
					+ getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void getSession() {
		disposeException = ((ComStaticApp) getApplication()).getDisposeException();
	}

	private void addListeners() {
		btnLogin.setOnClickListener(btnListener);
		btnCancel.setOnClickListener(btnListener);
	}

	private View.OnClickListener btnListener = new View.OnClickListener() {

		public void onClick(View v) {
			Button button = (Button) v;
			switch (button.getId()) {
				case R.id.btnLogin :
					userid = txtUserid.getText().toString().trim();
					userpwd = txtUserpwd.getText().toString().trim();
					userid = "54000252";
					userpwd = "123456";
					if (!validate(userid, userpwd)) {
						break;
					}
					thread = new HttpThread(handler);
					thread.doStart(userid, userpwd);
					break;
				case R.id.btnCancel :
					sp = Login.this.getPreferences(MODE_PRIVATE);
					SharedPreferences.Editor editor = sp.edit();
					if (!chkUserid.isChecked() && !chkUserpwd.isChecked()) {
						editor.clear();
						chkUserid.setChecked(false);
						chkUserpwd.setChecked(false);
					} else if (!chkUserid.isChecked()) {
						editor.remove("userid");
						chkUserid.setChecked(false);
					} else if (!chkUserpwd.isChecked()) {
						editor.remove("userpwd");
						chkUserpwd.setChecked(false);
					}
					editor.commit();
					Login.this.finish();
					break;
			}
		}
	};

	private class HttpThread extends Thread {
		private Handler handle = null;
		private String userid = null;
		private String userpwd = null;
		private boolean newVersion = false;

		public HttpThread(Handler hander) {
			handle = hander;
		}

		private void doStart(String userid, String userpwd) {
			this.userid = userid;
			this.userpwd = userpwd;
			progressDialog = new ProgressDialog(Login.this);
			progressDialog.setTitle("提示信息");
			progressDialog.setMessage("正在请求数据，请稍等......");
			progressDialog.setCancelable(false);
			progressDialog.show();

			this.start();
		}

		public void run() {
			Message message = null;
			try {
				autoUpdateService = new AutoUpdateService(Login.this);
				int versionCode = autoUpdateService.getCurrentVersion();
				LoginOpeService service = new LoginOpeService();
				String result = service.LoginAndroidVer();
				if (Integer.parseInt(result) != versionCode
						&& Integer.parseInt(result) > versionCode) {
					newVersion = true;
					progressDialog.dismiss();
					message = handle.obtainMessage();
					bundle = new Bundle();
					message.what = CommonStatic.STATE_NORMAL;
					bundle.putBoolean("newVersion", newVersion);
				} else {
					LoginOpeService loginService = new LoginOpeService();
					List<LoginInfoBean> list = loginService.UserLogin(userid, userpwd);
					OrderOpeService unitInfoService = new OrderOpeService();
					List<UnitInfoBean> listUnitInfo = unitInfoService.GetUnit();
					NoteOpeService noteOpeService = new NoteOpeService();
					String newTaskRemind = noteOpeService.GetHasNewTask(userid);
					LoginInfoBean loginInfo = list.get(0);
					if ("Y".equals(loginInfo.getRunstate())) {
						progressDialog.dismiss();
						message = handle.obtainMessage();
						bundle = new Bundle();
						message.what = CommonStatic.STATE_NORMAL;
						bundle.putBoolean("flag", true);
						loginInfo.setPernr(userid);
						bundle.putSerializable("loginInfo", loginInfo);
						bundle.putString("newTaskRemind", newTaskRemind);
						bundle.putSerializable("listUnitInfo", (Serializable) listUnitInfo);
					} else {
						progressDialog.dismiss();
						message = handle.obtainMessage();
						bundle = new Bundle();
						message.what = CommonStatic.STATE_NORMAL;
						bundle.putBoolean("flag", false);
					}
				}
				message.setData(bundle);
				handle.sendMessage(message);
			} catch (Exception ex) {
				progressDialog.dismiss();
				disposeException.handleException(ex);
			}
		}
	}

	private Handler handler = new Handler() {
		private boolean newVersion = false;

		@SuppressWarnings("unchecked")
		public void handleMessage(Message m) {
			newVersion = m.getData().getBoolean("newVersion");
			switch (m.what) {
				case CommonStatic.STATE_NORMAL :
					if (newVersion) {
						autoUpdateService.showUpdateDialog();
					} else {
						flag = m.getData().getBoolean("flag");
						LoginInfoBean loginInfo = (LoginInfoBean) m.getData().getSerializable(
								"loginInfo");
						List<UnitInfoBean> listUnitInfo = (List<UnitInfoBean>) m.getData()
								.getSerializable("listUnitInfo");
						String newTaskRemind = m.getData().getString("newTaskRemind");
						if (flag) {
							remember(userid, userpwd);
							bundle = new Bundle();
							bundle.putSerializable("loginInfo", loginInfo);
							bundle.putSerializable("listUnitInfo", (Serializable) listUnitInfo);
							bundle.putString("newTaskRemind", newTaskRemind);

							Intent intent = new Intent(Login.this, Main.class);//activity跳转信息
							intent.putExtras(bundle);
							Login.this.startActivity(intent);
						} else {
							new AlertDialog.Builder(Login.this).setTitle("提示信息")
									.setMessage("用户名或者密码不正确!").setNeutralButton("关闭", null).show();
							txtUserpwd.setText("");
						}
					}
					break;
			}
		}
	};

	private void checkIfRemember() {
		sp = this.getPreferences(MODE_PRIVATE);
		String userid = sp.getString("userid", null);
		String userpwd = sp.getString("userpwd", null);
		if (null != userid && !"".equals(userid)) {
			txtUserid.setText(userid);
			chkUserid.setChecked(true);
		}
		if (null != userpwd && !"".equals(userpwd)) {
			txtUserpwd.setText(userpwd);
			chkUserpwd.setChecked(true);
		}
	}

	private boolean validate(String userid, String userpwd) {
		if ("".equals(userid)) {
			this.showDialog(getResources().getString(R.string.info_1));
			return false;
		}
		if ("".equals(userpwd)) {
			this.showDialog(getResources().getString(R.string.info_2));
			return false;
		}
		return true;
	}

	private void remember(String userid, String userpwd) {
		sp = this.getPreferences(MODE_PRIVATE);
		SharedPreferences.Editor editor = sp.edit();
		editor.clear();
		if (chkUserid.isChecked() && chkUserpwd.isChecked()) {
			editor.putString("userid", userid);
			editor.putString("userpwd", userpwd);
		} else if (chkUserid.isChecked()) {
			editor.putString("userid", userid);
		} else if (chkUserpwd.isChecked()) {
			editor.putString("userpwd", userpwd);
		}
		editor.commit();
	}

	protected void setLoadingState(Boolean newState) {
		synchronized (isLoading) {
			if (newState && !isLoading) {
				progressDialog = ProgressDialog.show(this, getResources()
						.getString(R.string.info_4), getResources().getString(R.string.info_5),
						true);
			} else if (!newState && progressDialog != null) {
				progressDialog.dismiss();
			}
			isLoading = newState;
		}
	}

	private void showDialog(String msg) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(msg).setCancelable(false).setPositiveButton(R.string.submit, null);
		AlertDialog alert = builder.create();
		alert.show();
	}
}
